/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode cur = new ListNode(-1);
        cur.next = head;
        ListNode ans = cur;
        
        int length = getLength(head);
        int n2 = length - n;
        for(int i = 0; i < n2; i++){
            cur = cur.next;
        }
        ListNode curNode = cur.next;
        cur.next = curNode.next;
        return ans.next;
    }
     public int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            ++length;
            head = head.next;
        }
        return length;
     }
}